﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;

public partial class CloseFinancialYear : System.Web.UI.Page, ICallbackEventHandler
{
    Dictionary<string, string> ClientRequest = null;
    Dictionary<string, string> ClientResponse = null;
    JavaScriptSerializer serializer;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsCallback)
        {
            CallBackReference();
            if (!IsPostBack)
            {
                if (SessionInfo.prop_getObj.EmployeeID == 0)
                    Response.Redirect("login.aspx");
                else
                {
                    hdnExportToExcelFilePath.Value = GlobalDefaultValues.DHTMLXExportToExcelFilePath;
                    PLMstFormMasters objRights = CommonUtil.CheckRightsForForm("2");
                    if (objRights.ViewAccess == false)
                        Response.Redirect("Login.aspx");
                    cboStatus.Focus();
                    PLFinanceYear plObj = new BL_FinanceYear().BL_fnGetCurrentFinancialYear();

                    if (Request.Params.Count > 0 && Request.Params[0] == "Excel")
                    {
                        UI_ExportToExcel(plObj.FinancialYearID);
                    }


                    if (plObj != null)
                    {
                        hdnFinancialYearID.Value = plObj.FinancialYearID.ToString();
                        txtFinYear.Text = "Financial Year : " + plObj.FinYearStartDate.Value.ToString("MMM-yy") + "-" + plObj.FinYearEndDate.Value.ToString("MMM-yy");
                        txtFinYear.Enabled = false;
                        txtFinYear.ReadOnly = true;
                    }
                    else
                    {
                        btnCloseMuster.Visible = false;
                        btnSearch.Visible = false;

                    }
                }
            }
        }
    }

    // Override the Render method to ensure that this control
    // is nested in an HtmlForm server control, between a <form runat=server>
    // opening tag and a </form> closing tag.
    protected override void Render(HtmlTextWriter writer)
    {
        // Ensure that the control is nested in a server form.
        if (Page != null)
        {
            Page.VerifyRenderingInServerForm(this);
        }
        base.Render(writer);
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }

    protected void UI_ExportToExcel(int pIntFinancialYearID)
    {
        string strCompletedContractIDs = new BL_FinanceYear().BL_fnGetCompletedContractDetails();
        int intIncrementer = 0;
        if (SessionInfo.prop_getObj.CloseFinancialYearOption == "Contract")
        {
            PLContract plObj = new PLContract();
            plObj.FinancialYearIDs = "0";
            plObj.SearchIsActive = true;
            plObj.IsCompleted = true;
            plObj.TrnContractIDs = strCompletedContractIDs;
            List<PLContract> objContractList = new BL_Contract().BL_fnGetContractTransactions(plObj);
            var varInvList = (from l in objContractList
                              select new
                              {
                                  SrNo = intIncrementer++,
                                  ContractNo = l.ContractNo,
                                  CompanyName = l.CompanyName,
                                  ClientName = l.ClientName,
                                  ContractName = l.ContractName,
                                  PaymentModeName = l.PaymentModeName,
                                  ContractStartDate = l.ContractStartDate.Value.ToString("dd/MM/yyyy"),
                                  ContractAmount = l.ContractAmount,
                                  IsActive = (l.IsActive == true ? "Active" : "InActive")
                              });
            List<string> lstHeader = new List<string>() { "Sr.", "Contract#", "Company", "Client", "Contract", "Payment Mode", "Contract Start Date", "Contract Amt.", "Status" };
            CommonUtil.ExportToExcelWithEPPlus(lstHeader, varInvList, Response, "Contract List");
        }
        else if (SessionInfo.prop_getObj.CloseFinancialYearOption == "Invoice")
        {
            PLInvoice plObj = new PLInvoice();
            plObj.TrnContractIDs = strCompletedContractIDs;
            plObj.SearchIsActive = true;
            plObj.IsCompleted = true;
            List<PLInvoice> objInvoiceList = new BL_Invoice().BL_fnGetInvoiceReport(plObj);
            var varInvList = (from l in objInvoiceList
                              select new
                              {
                                  SrNo = intIncrementer++,
                                  Company = l.CompanyName,
                                  Client = l.ClientName,
                                  Contract = l.ContractName,
                                  PaymentMode = l.PaymentModeName,
                                  PaymentLevelName = l.PaymentLevelName,
                                  ContractNo = l.ContractNo,
                                  InvoiceNo = l.InvoiceNo,
                                  InvoiceDate = l.InvoiceDate.ToString("dd/MM/yyyy"), 
                                  ContractPer = l.PaymentLevelPer,
                                  GrossAmt = l.GrossInvoiceAmount,
                                  ServiceTaxPer = l.ServiceTaxPer,
                                  ServiceTaxAmt = l.ServiceTaxAmount,
                                  FinalInvAmt = l.FinalInvoiceAmount
                              });
            List<string> lstHeader = new List<string>() { "Sr.", "Company", "Client", "Contract", "Payment Mode", "Payment Level", "Contract #", "Invoice #", "Invoice Date", "Contract %", "Gross Amt.", "Service Tax %", "Service Tax Amt.", "Final Invoice Amt." };
            CommonUtil.ExportToExcelWithEPPlus(lstHeader, varInvList, Response, "Invoice List");
        }
        else if (SessionInfo.prop_getObj.CloseFinancialYearOption == "Collection")
        {
            PLCollection plObj = new PLCollection();
            plObj.TranContractIDs = strCompletedContractIDs;
            List<PLCollection> objCollection = new BL_Collection().BL_GetCollectionReport(plObj);
            var varInvList = (from l in objCollection
                              select new
                              {
                                  SrNo = intIncrementer++,
                                  CompanyName = l.CompanyName,
                                  ClientName = l.ClientName,
                                  ContractName = l.ContractName,
                                  InvoiceNo = l.InvoiceNo,
                                  CollectionNo = l.CollectionNo,
                                  CollectionDate = l.CollectionDate.ToString("dd/MM/yyyy"), 
                                  CollectionType = l.CollectionType,
                                  DrawnOnBank = l.DrawnOnBank,
                                  CollectionRefNo = l.CollectionRefNo,
                                  Amount = l.Amount,
                                  TDSAmount = l.TDSAmount,
                                  GrossAmount = l.GrossAmount,
                                  Remarks = l.Remarks
                              });
            List<string> lstHeader = new List<string>() { "Sr.", "Company", "Client", "Contract", "Invoice #", "Collection #", "Collection Date", "Collection Type", "Drawn Bank", "Ref. No.", "Amount", "TDS Amount", "Gross Amount", "Remarks" };
            CommonUtil.ExportToExcelWithEPPlus(lstHeader, varInvList, Response, "Collection List");
        }
        else if (SessionInfo.prop_getObj.CloseFinancialYearOption == "Full")
        {
            PLCollection plObj = new PLCollection();
            plObj.TranContractIDs = strCompletedContractIDs; 
            List<PLCollection> objCollection = new BL_Collection().BL_GetCollectionReportFull(plObj);
            var varInvList = (from l in objCollection
                              select new
                              {
                                  SrNo = intIncrementer++,
                                  ContractNo = l.ContractNo,
                                  InvoiceNo = l.InvoiceNo,
                                  CollectionNo = l.CollectionNo,
                                  CompanyName = l.CompanyName,
                                  ClientName = l.ClientName,
                                  ContractName = l.ContractName,
                                  PaymentModeName = l.PaymentModeName,
                                  PaymentLevelName = l.PaymentLevelName, 
                                  ContractStartDate = l.ContractStartDate.Value.ToString("dd/MM/yyyy"),
                                  ContractAmount = l.ContractAmount,
                                  InvoiceDate = l.InvoiceDate.Value.ToString("dd/MM/yyyy"),
                                  ContractPer = l.ContractPer,
                                  InvGrossAmount = l.InvGrossAmount,
                                  ServiceTaxPer = l.ServiceTaxPer,
                                  ServiceTaxAmount = l.ServiceTaxAmount,
                                  FinalInvoiceAmount = l.FinalInvoiceAmount,
                                  CollectionDate = l.CollectionDate.ToString("dd/MM/yyyy"),
                                  CollectionType = l.CollectionType,
                                  DrawnOnBank = l.DrawnOnBank,
                                  CollectionRefNo = l.CollectionRefNo,
                                  Amount = l.Amount,
                                  TDSAmount = l.TDSAmount,
                                  GrossAmount = l.GrossAmount,
                                  Remarks = l.Remarks
                              });
            List<string> lstHeader = new List<string>() { "Sr.", "Contract #", "Invoice #", "Collection #", "Company", "Client", "Contract", "Payment Mode", "Payment Level", "Contract Start Date", "Contract Amt.", "Invoice Date", "Contract %", "Gross Amt.", "Service Tax %", "Service Tax Amt.", "Final Invoice Amt.", "Collection Date", "Collection Type", "Drawn Bank", "Ref. No.", "Collection Amt.", "TDS Amount", "Collection Gross Amount", "Collection Remarks" };
            CommonUtil.ExportToExcelWithEPPlus(lstHeader, varInvList, Response, "Collection List");
        } 
    }


    #region callback functions
    public void CallBackReference()
    {
        string strReference = Page.ClientScript.GetCallbackEventReference(this, "args", "getResponse", "context", "ClientCallbackError", true);
        string strScript = " function UseCallback(args,context) { " + strReference + " ; } ";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "UseCallback", strScript, true);
    }

    public string GetCallbackResult()
    {
        System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        oSerializer.MaxJsonLength = GlobalDefaultValues.MaxJsonLength;
        return oSerializer.Serialize(ClientResponse);
    }

    public void RaiseCallbackEvent(string strEventArgument)
    {
        try
        {
            serializer = new JavaScriptSerializer();
            ClientRequest = serializer.Deserialize<Dictionary<string, string>>(strEventArgument);
            ClientResponse = new Dictionary<string, string>();
            string Track = ClientRequest["Track"];
            ClientResponse = new Dictionary<string, string>();
            ClientResponse["Track"] = Track;
            if (SessionInfo.prop_getObj.EmployeeID == 0)
            {
                ClientResponse["SessionTimeOut"] = "1";
            }
            else
            {
                ClientResponse["SessionTimeOut"] = "0";
                if (Track.Equals("GetSearchResult"))
                {
                    UI_SearchResult();
                }
            }
        }
        catch (Exception ex)
        {
            CommonUtil.Elmah_SignalException(ex, this.Context, "User Master - Method: RaiseCallbackEvent()");
        }
    }

    private void UI_SearchResult()
    {
        string strCompletedContractIDs = new BL_FinanceYear().BL_fnGetCompletedContractDetails();
        PLFinanceYear objFinYear = new PLFinanceYear();
        string strStatus = ClientRequest[cboStatus.ID];
        GridView grdView;
        SessionInfo.prop_getObj.CloseFinancialYearOption = strStatus;
        if (strStatus == "Contract")
        {
            PLContract plObj = new PLContract();
            plObj.FinancialYearIDs = "0";
            plObj.SearchIsActive = true;
            plObj.IsCompleted = true;
            plObj.TrnContractIDs = strCompletedContractIDs;
            List<PLContract> objContractList = new BL_Contract().BL_fnGetContractTransactions(plObj);
            grdView = grdContract;
            grdView.DataSource = objContractList;
        }
        else if (strStatus == "Invoice")
        {
            PLInvoice plObj = new PLInvoice();
            plObj.TrnContractIDs = strCompletedContractIDs;
            plObj.SearchIsActive = true;
            plObj.IsCompleted = true;
            List<PLInvoice> objInvoiceList = new BL_Invoice().BL_fnGetInvoiceReport(plObj);
            grdView = grdInvoice;
            grdView.DataSource = objInvoiceList;
        }
        else if (strStatus == "Collection")
        {
            PLCollection plObj = new PLCollection();
            plObj.TranContractIDs = strCompletedContractIDs;
            List<PLCollection> objCollection = new BL_Collection().BL_GetCollectionReport(plObj);
            grdView = grdCollection;
            grdView.DataSource = objCollection;
        }
        else if (strStatus == "Full")
        {
            PLInvoice plObj = new PLInvoice();
            plObj.TrnContractIDs = strCompletedContractIDs;
            plObj.SearchIsActive = true;
            plObj.IsCompleted = true;
            List<PLInvoice> objInvoiceList = new BL_Invoice().BL_fnGetInvoiceReport(plObj);
            grdView = grdFull;
            grdView.DataSource = objInvoiceList;
        }
        else
            grdView = null;

        grdView.DataBind();
        ClientResponse["GridName"] = grdView.Parent.ID;
        ClientResponse["GridResult"] = CommonUtil.GetRenderControl(grdView);
    }

    protected void grdResult_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[0].Text = (e.Row.RowIndex + 1).ToString();
        }
    }
    #endregion

}